﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EFong.Data;
using EFong.BL.Const;
using System.Diagnostics;

namespace EFong.BL
{
    public class MasterBL
    {
        #region Static Data

        private EFongEntities entities = EFongEntitiesManager.GetInstance();

        private List<Contract.Project> _projectList;
        private List<Contract.Project> _ProjectList
        {
            get
            {
                if (_projectList == null)
                {

                    _projectList = (from p in entities.Project
                                    orderby p.Seq
                                    select new Contract.Project()
                                     {
                                         ID = p.ID,
                                         Name = p.Name.Trim(),
                                         Effective = p.Effective,
                                         Seq = p.Seq,
                                         ReportStyle = p.ReportStyle,
                                         Editable = p.Editable
                                     }).ToList();
                    foreach (Contract.Project project in _projectList)
                    {
                        project.SubProjectList = (from sp in entities.SubProject
                                                  where sp.ProjectID.Equals(project.ID)
                                                  orderby sp.Seq
                                                  select new Contract.SubProject()
                                                  {
                                                      ID = sp.ID,
                                                      Name = sp.Name.Trim(),
                                                      Seq = sp.Seq,
                                                      Effective = sp.Effective
                                                  }
                                                  ).ToList();
                    }

                }

                return _projectList;
            }
        }

        #endregion

        #region Method

        public List<Contract.Project> GetAllProject()
        {
            return _ProjectList;
        }

        public List<Contract.Project> GetAllOtherProject()
        {
            return _ProjectList.FindAll(p => p.Editable == true);
        }

        public Contract.Project GetProjectByID(Guid id)
        {
            return _ProjectList.Find(p => p.ID == id);
        }

        public void NewProject(Contract.Project project)
        {

            Project oldProject = (from p in entities.Project
                                  where p.Name == project.Name
                                  select p).SingleOrDefault();
            if (oldProject != null)
                throw new BusinessException(CommonFail.项目已存在);

            Project newProject = new Project()
            {
                ID = project.ID,
                Name = project.Name.Trim(),
                Effective = project.Effective,
                ReportStyle = project.ReportStyle,
                Seq = project.Seq,
                Editable = true
            };
            entities.AddToProject(newProject);

            foreach (Contract.SubProject subProject in project.SubProjectList)
            {
                SubProject newSubProject = new SubProject();
                newSubProject.ID = subProject.ID;
                newSubProject.Name = subProject.Name;
                newSubProject.ProjectID = project.ID;
                newSubProject.Seq = subProject.Seq;
                newSubProject.Effective = subProject.Effective;

                entities.AddToSubProject(newSubProject);
            }

            entities.SaveChanges();

            _projectList = null;
        }

        public void UpdateProject(Contract.Project project)
        {

            Project oldProject = (from p in entities.Project
                                  where p.ID== project.ID
                                  select p).SingleOrDefault();
            if (oldProject == null)
            {
                Project newProject = new Project()
                {
                    ID = project.ID,
                    Name = project.Name.Trim(),
                    Effective = project.Effective,
                    ReportStyle = project.ReportStyle,
                    Seq = project.Seq,
                    Editable = true
                };
                entities.AddToProject(newProject);

                foreach (Contract.SubProject subProject in project.SubProjectList)
                {
                    SubProject newSubProject = new SubProject();
                    newSubProject.ID = subProject.ID;
                    newSubProject.Name = subProject.Name;
                    newSubProject.ProjectID = project.ID;
                    newSubProject.Seq = subProject.Seq;
                    newSubProject.Effective = subProject.Effective;

                    entities.AddToSubProject(newSubProject);
                }
            }
            else
            {
                //if (!oldProject.Editable)
                //    throw new BusinessException(CommonFail.项目不能编辑, new Contract.FailValue("Project", project));

                oldProject.Name = project.Name;
                oldProject.Effective = project.Effective;
                oldProject.ReportStyle = project.ReportStyle;
                oldProject.Seq = project.Seq;

                foreach (Contract.SubProject subProject in project.SubProjectList)
                {
                    SubProject oldSubProject = (from sp in entities.SubProject
                                                where sp.ID.Equals(subProject.ID)
                                                select sp).SingleOrDefault();
                    if (oldSubProject == null)
                    {
                        SubProject newSubProject = new SubProject();
                        newSubProject.ID = subProject.ID;
                        newSubProject.Name = subProject.Name;
                        newSubProject.ProjectID = project.ID;
                        newSubProject.Seq = subProject.Seq;
                        newSubProject.Effective = subProject.Effective;

                        entities.AddToSubProject(newSubProject);
                    }
                    else
                    {
                        oldSubProject.Seq = subProject.Seq;
                        oldSubProject.Effective = subProject.Effective;
                    }
                }
            }
            entities.SaveChanges();

            _projectList = null;
        }

        public void UpdateProjectList(List<Contract.Project> projectList)
        {
            checkProjectList(projectList);
            foreach (Contract.Project project in projectList)
            {

                Project oldProject = (from p in entities.Project
                                      where p.Name == project.Name
                                      select p).SingleOrDefault();
                if (oldProject == null)
                {
                    Project newProject = new Project()
                    {
                        ID = project.ID,
                        Name = project.Name.Trim(),
                        Effective = project.Effective,
                        ReportStyle = project.ReportStyle,
                        Seq = project.Seq,
                        Editable = true
                    };
                    entities.AddToProject(newProject);

                    foreach (Contract.SubProject subProject in project.SubProjectList)
                    {
                        SubProject newSubProject = new SubProject();
                        newSubProject.ID = subProject.ID;
                        newSubProject.Name = subProject.Name;
                        newSubProject.ProjectID = project.ID;
                        newSubProject.Seq = subProject.Seq;
                        newSubProject.Effective = subProject.Effective;

                        entities.AddToSubProject(newSubProject);
                    }
                }
                //if (!oldProject.Editable)
                //    throw new BusinessException(CommonFail.项目不能编辑, new Contract.FailValue("Project", project));

                oldProject.Effective = project.Effective;
                oldProject.ReportStyle = project.ReportStyle;
                oldProject.Seq = project.Seq;

                foreach (Contract.SubProject subProject in project.SubProjectList)
                {
                    SubProject oldSubProject = (from sp in entities.SubProject
                                                where sp.ID.Equals(subProject.ID)
                                                select sp).SingleOrDefault();
                    if (oldSubProject == null)
                    {
                        SubProject newSubProject = new SubProject();
                        newSubProject.ID = subProject.ID;
                        newSubProject.Name = subProject.Name;
                        newSubProject.ProjectID = project.ID;
                        newSubProject.Seq = subProject.Seq;
                        newSubProject.Effective = subProject.Effective;

                        entities.AddToSubProject(newSubProject);
                    }
                    else
                    {
                        oldSubProject.Seq = subProject.Seq;
                        oldSubProject.Effective = subProject.Effective;
                    }
                }

                entities.SaveChanges();
                _projectList = null;
            }
        }

        private void checkProjectList(List<Contract.Project> projectList)
        {
            for (int i = 0; i < projectList.Count; i++)
            {
                Contract.Project project = projectList[i];

                project.Name = project.Name.Trim();
                project.Seq = i;
                if (project.Name == string.Empty)
                    throw new BusinessException(VerificationText.请输入项目名称);

                checkSubProjectList(project.SubProjectList);
            }
        }

        private void checkSubProjectList(List<Contract.SubProject> subProjectList)
        {
            for (int i = 0; i < subProjectList.Count; i++)
            {
                Contract.SubProject subProject = subProjectList[i];

                subProject.Name = subProject.Name.Trim();
                subProject.Seq = i;
                if (subProject.Name == string.Empty)
                    throw new BusinessException(VerificationText.请输入细项名称);
            }
        }

        public List<Contract.BankAccount> GetAllBankAccount()
        {

            var list = (from ba in entities.BankAccount
                        select new Contract.BankAccount()
                        {
                            ID = ba.ID,
                            Name = ba.Name.Trim(),
                            Effective = ba.Effective,
                            CanNegative = ba.CanNegative,
                            Amount = ba.Amount,
                            IsNew = false,
                            Currency = (from c in entities.Currency
                                        where c.ID == ba.CurrencyID
                                        select new Contract.Currency()
                                        {
                                            ID = c.ID,
                                            Name = c.Name.Trim(),
                                            Code = c.Code.Trim(),
                                            ExchangeRate = (from er in entities.ExchangeRate
                                                            where er.SourceCurrencyID.Equals(c.ID)
                                                            select er.Rate).FirstOrDefault()
                                        }).FirstOrDefault()
                        }).ToList();

            return list;
        }

        public Contract.BankAccount GetBankAccountByID(Guid id)
        {
            Contract.BankAccount bankAccount =
                (from ba in entities.BankAccount
                 where ba.ID == id
                 select new Contract.BankAccount()
                 {
                     ID = ba.ID,
                     Name = ba.Name.Trim(),
                     Effective = ba.Effective,
                     CanNegative = ba.CanNegative,
                     Amount = ba.Amount,
                     Currency = new Contract.Currency() { ID = ba.CurrencyID }
                 }).SingleOrDefault();

            bankAccount.Currency = new BaseBL().GetCurrencyByID(bankAccount.Currency.ID);

            return bankAccount;
        }

        public void NewBankAccount(Contract.BankAccount bankAccount)
        {
            checkBankAccount(bankAccount);


            BankAccount oldBankAccount = (from ba in entities.BankAccount
                                          where ba.Name == bankAccount.Name
                                          select ba).SingleOrDefault();
            if (oldBankAccount != null)
                throw new BusinessException(CommonFail.银行账户已存在);

            BankAccount newBankAccount = new BankAccount()
            {
                ID = bankAccount.ID,
                Name = bankAccount.Name,
                Effective = bankAccount.Effective,
                Amount = bankAccount.Amount,
                CanNegative = bankAccount.CanNegative,
                ReturnDay = bankAccount.ReturnDay,
                CurrencyID = bankAccount.Currency.ID
            };
            entities.AddToBankAccount(newBankAccount);

            entities.SaveChanges();
        }

        private void checkBankAccount(Contract.BankAccount bankAccount)
        {
            bankAccount.Name = bankAccount.Name.Trim();
            if (bankAccount.Name == string.Empty)
                throw new BusinessException(VerificationText.请输入银行帐号名称);
        }

        public void UpdateBankAccounts(List<Contract.BankAccount> lstbankAccount)
        {
            foreach (var eachBankAccount in lstbankAccount)
            {
                UpdateBankAccount(eachBankAccount);
            }
        }

        public void UpdateBankAccount(Contract.BankAccount bankAccount)
        {
            checkBankAccount(bankAccount);


            BankAccount oldBankAccount = (from ba in entities.BankAccount
                                          where ba.Name == bankAccount.Name
                                          select ba).SingleOrDefault();
            if (oldBankAccount == null)
            {
                NewBankAccount(bankAccount);
                return;
            }

            oldBankAccount.CanNegative = bankAccount.CanNegative;
            oldBankAccount.ReturnDay = bankAccount.ReturnDay;
            oldBankAccount.Name = bankAccount.Name;
            oldBankAccount.Effective = bankAccount.Effective;
            oldBankAccount.Amount = bankAccount.Amount;

            entities.SaveChanges();
        }

        public List<Contract.RCustomer> GetAllCustomer()
        {
            //Stopwatch sw = new Stopwatch();

            //sw.Start();
            List<Contract.RCustomer> customerList =
                (from c in entities.Customer
                 orderby c.Nr
                 select new Contract.RCustomer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     Intergral = c.Intergral,
                     ContactPersonTel = c.ContactPerson1Tel,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Remark = c.Remark.Trim(),
                 }).ToList();

            //sw.Stop();
            //Console.WriteLine(sw.Elapsed);

            return customerList;
        }

        public List<Contract.RCustomer> GetCustomerByName(string name)
        {
            List<Contract.RCustomer> customerList =
                (from c in entities.Customer
                 where c.Name.IndexOf(name.Trim()) >= 0
                 orderby c.Nr
                 select new Contract.RCustomer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     Intergral = c.Intergral,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Remark = c.Remark.Trim(),
                 }).ToList();

            return customerList;
        }

        public List<Contract.RCustomer> GetCustomerByAddress(string address)
        {
            List<Contract.RCustomer> customerList =
                (from c in entities.Customer
                 where c.Address.IndexOf(address.Trim()) >= 0
                 orderby c.Nr
                 select new Contract.RCustomer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     Intergral = c.Intergral,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Remark = c.Remark.Trim(),
                 }).ToList();

            return customerList;
        }

        public List<Contract.RCustomer> GetCustomerByTel(string tel)
        {
            List<Contract.RCustomer> customerList =
                (from c in entities.Customer
                 where c.ContactPerson1Phone1.IndexOf(tel.Trim()) >= 0 ||
                       c.ContactPerson1Phone2.IndexOf(tel.Trim()) >= 0 ||
                       c.ContactPerson1Tel.IndexOf(tel.Trim()) >= 0 ||
                       c.ContactPerson2Phone1.IndexOf(tel.Trim()) >= 0 ||
                       c.ContactPerson1Phone2.IndexOf(tel.Trim()) >= 0 ||
                       c.ContactPerson2Tel.IndexOf(tel.Trim()) >= 0 ||
                       c.FinancialAffairsPhone1.IndexOf(tel.Trim()) >= 0 ||
                       c.FinancialAffairsPhone2.IndexOf(tel.Trim()) >= 0 ||
                       c.FinancialAffairsTel.IndexOf(tel.Trim()) >= 0
                 orderby c.Nr
                 select new Contract.RCustomer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     Intergral = c.Intergral,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Remark = c.Remark.Trim(),
                 }).ToList();

            return customerList;
        }

        public List<Contract.RCustomer> GetCustomerBySalesman(Contract.User salesman)
        {
            List<Contract.RCustomer> customerList =
                (from c in entities.Customer
                 where c.SalesmanID == salesman.ID
                 orderby c.Nr
                 select new Contract.RCustomer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     Intergral = c.Intergral,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Remark = c.Remark.Trim(),
                 }).ToList();

            return customerList;
        }

        public Contract.RCustomer GetRCustomerByID(Guid id)
        {
            return (from c in entities.Customer
                    where c.ID == id
                    select new Contract.RCustomer()
                    {
                        ID = c.ID,
                        Address = c.Address.Trim(),
                        Intergral = c.Intergral,
                        Name = c.Name.Trim(),
                        Nr = c.Nr.Trim(),
                        Remark = c.Remark.Trim(),
                    }).SingleOrDefault();
        }

        public Contract.Customer GetCustomerByID(Guid id)
        {

            Contract.Customer customer =
                (from c in entities.Customer
                 where c.ID == id
                 select new Contract.Customer()
                 {
                     ID = c.ID,
                     Address = c.Address.Trim(),
                     ContactPerson1 = c.ContactPerson1.Trim(),
                     ContactPerson2 = c.ContactPerson2.Trim(),
                     ContactPerson1Phone1 = c.ContactPerson1Phone1.Trim(),
                     ContactPerson1Phone2 = c.ContactPerson1Phone2.Trim(),
                     ContactPerson2Phone1 = c.ContactPerson2Phone1.Trim(),
                     ContactPerson2Phone2 = c.ContactPerson2Phone2.Trim(),
                     ContactPerson1Tel = c.ContactPerson1Tel.Trim(),
                     ContactPerson2Tel = c.ContactPerson2Tel.Trim(),
                     Fax = c.Fax.Trim(),
                     FinancialAffairs = c.FinancialAffairs.Trim(),
                     FinancialAffairsPhone1 = c.FinancialAffairsPhone1.Trim(),
                     FinancialAffairsPhone2 = c.FinancialAffairsPhone2.Trim(),
                     FinancialAffairsTel = c.FinancialAffairsTel.Trim(),
                     FlightIntergralRate = c.FlightIntergralRate,
                     Intergral = c.Intergral,
                     Name = c.Name.Trim(),
                     Nr = c.Nr.Trim(),
                     Amount = c.Amount.Value,
                     Remark = c.Remark.Trim(),
                     HotelIntergralRate = c.HotelIntergralRate,
                     Salesman = (from u in entities.User
                                 where u.ID == c.SalesmanID
                                 select new Contract.User()
                                 {
                                     ID = u.ID,
                                     Name = u.Name.Trim(),
                                     Staff = u.Staff.Trim()
                                 }).FirstOrDefault(),
                     WebUser = (from w in entities.WebUser
                                where w.ID == c.WebUserID
                                select new Contract.WebUser()
                                {
                                    ID = w.ID,
                                    Name = w.Name.Trim(),
                                    Password = w.Password.Trim()
                                }).FirstOrDefault(),
                 }).SingleOrDefault();

            if (customer == null)
                throw new BusinessException(CommonFail.客户不存在);

            customer.HotelIntergralList =
                (from ch in entities.CustomerHotelIntergralRate
                 where ch.CustomerID == customer.ID
                 orderby ch.HotelLevelID
                 select new Contract.CustomerHotelIntergralRate()
                 {
                     ID = ch.ID,
                     Intergral = ch.Intergral,
                     HotelLevel = (from hl in entities.HotelLevel
                                   where hl.ID == ch.HotelLevelID
                                   select new Contract.HotelLevel()
                                   {
                                       ID = hl.ID,
                                       Name = hl.Name.Trim()
                                   }).FirstOrDefault()
                 }).ToList();

            customer.PassengerList =
                (from p in entities.Passenger
                 where p.CustomerID == customer.ID
                 select new Contract.Passenger()
                 {
                     ID = p.ID,
                     BirthDay = p.BirthDay,
                     CName = p.CName.Trim(),
                     Effective = p.Effective,
                     EName = p.EName.Trim(),
                     FlightCard1 = p.FlightCard1.Trim(),
                     FlightCard2 = p.FlightCard2.Trim(),
                     FlightCard3 = p.FlightCard3.Trim(),
                     IDCardNr1 = p.IDCardNr1.Trim(),
                     IDCardNr2 = p.IDCardNr2.Trim(),
                     IDCardType1 = p.IDCardType1.Trim(),
                     IDCardType2 = p.IDCardType2.Trim(),
                     IDCardEffective1 = p.IDCardEffective1,
                     IDCardEffective2 = p.IDCardEffective2,
                     Nation = p.Nation.Trim(),
                     Sex = p.Sex.Trim(),
                     Tel1 = p.Tel1.Trim(),
                     Tel2 = p.Tel2.Trim()
                 }).ToList();

            customer.IntergralExchangeHistory =
                (from ie in entities.IntergralExchange
                 where ie.CustomerID == customer.ID
                 orderby ie.UpdateTime
                 select new Contract.IntergralExchange()
                 {
                     ID = ie.ID,
                     Amount = ie.Amount,
                     CustomerText = ie.Customer.Name.Trim(),
                     Date = ie.Date,
                     Item = ie.Item.Trim(),
                     Qty = ie.Qty
                 }).ToList();

            return customer;
        }

        public string NewCustomer(Contract.Customer customer)
        {
            checkCustomer(customer);

            Customer oldCustomer = (from c in entities.Customer
                                    where c.Name == customer.Name
                                    select c).SingleOrDefault();
            if (oldCustomer != null)
                throw new BusinessException(CommonFail.客户已存在);

            Customer newCustomer = new Customer()
                 {
                     ID = customer.ID,
                     Address = customer.Address,
                     ContactPerson1 = customer.ContactPerson1,
                     ContactPerson2 = customer.ContactPerson2,
                     ContactPerson1Phone1 = customer.ContactPerson1Phone1,
                     ContactPerson1Phone2 = customer.ContactPerson1Phone2,
                     ContactPerson2Phone1 = customer.ContactPerson2Phone1,
                     ContactPerson2Phone2 = customer.ContactPerson2Phone2,
                     ContactPerson1Tel = customer.ContactPerson1Tel,
                     ContactPerson2Tel = customer.ContactPerson2Tel,
                     Fax = customer.Fax,
                     FinancialAffairs = customer.FinancialAffairs,
                     FinancialAffairsPhone1 = customer.FinancialAffairsPhone1,
                     FinancialAffairsPhone2 = customer.FinancialAffairsPhone2,
                     FinancialAffairsTel = customer.FinancialAffairsTel,
                     FlightIntergralRate = customer.FlightIntergralRate,
                     Intergral = customer.Intergral,
                     Name = customer.Name,
                     Nr = new BaseBL().GetNewNr("Customer"),
                     Remark = customer.Remark,
                     HotelIntergralRate = customer.HotelIntergralRate,
                     SalesmanID = customer.Salesman.ID,
                     Amount = customer.Amount,
                     CreateTime = DateTime.Now,
                     UpdateTime = DateTime.Now,
                 };

            if (customer.WebUser != null)
            {
                WebUser oldWebUser = (from wu in entities.WebUser
                                      where wu.ID == customer.WebUser.ID
                                      select wu).SingleOrDefault();
                if (oldWebUser == null)
                {
                    WebUser newWebUser = new WebUser()
                    {
                        ID = customer.WebUser.ID,
                        Name = customer.WebUser.Name,
                        Password = customer.WebUser.Password,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CreateParty = "程序"
                    };
                    entities.AddToWebUser(newWebUser);
                    newCustomer.WebUserID = newWebUser.ID;
                }
                else
                {
                    newCustomer.WebUserID = oldWebUser.ID;
                }
            }

            if (customer.HotelIntergralList.Count != 0)
                newCustomer.HotelIntergralRate = null;

            entities.AddToCustomer(newCustomer);

            foreach (Contract.CustomerHotelIntergralRate customerHotelIntergralRate in customer.HotelIntergralList)
            {
                CustomerHotelIntergralRate chir = new CustomerHotelIntergralRate()
                {
                    ID = customerHotelIntergralRate.ID,
                    Intergral = customerHotelIntergralRate.Intergral,
                    HotelLevelID = customerHotelIntergralRate.HotelLevel.ID,
                    CustomerID = customer.ID
                };
                entities.AddToCustomerHotelIntergralRate(chir);
            }


            foreach (Contract.Passenger passenger in customer.PassengerList)
            {
                Passenger newPassenger = new Passenger()
                {
                    ID = passenger.ID,
                    BirthDay = passenger.BirthDay,
                    CName = passenger.CName,
                    Effective = passenger.Effective,
                    EName = passenger.EName,
                    FlightCard1 = passenger.FlightCard1,
                    FlightCard2 = passenger.FlightCard2,
                    FlightCard3 = passenger.FlightCard3,
                    IDCardNr1 = passenger.IDCardNr1,
                    IDCardNr2 = passenger.IDCardNr2,
                    IDCardType1 = passenger.IDCardType1,
                    IDCardType2 = passenger.IDCardType2,
                    IDCardEffective1 = passenger.IDCardEffective1,
                    IDCardEffective2 = passenger.IDCardEffective2,
                    Nation = passenger.Nation,
                    Sex = passenger.Sex,
                    Tel1 = passenger.Tel1,
                    Tel2 = passenger.Tel2,
                    CustomerID = customer.ID,
                };
                entities.AddToPassenger(newPassenger);
            }

            entities.SaveChanges();

            return customer.Nr;
        }

        private void checkCustomer(Contract.Customer customer)
        {
            customer.Address = customer.Address.Trim();
            customer.ContactPerson1 = customer.ContactPerson1.Trim();
            customer.ContactPerson1Phone1 = customer.ContactPerson1Phone1.Trim();
            customer.ContactPerson1Phone2 = customer.ContactPerson1Phone2.Trim();
            customer.ContactPerson1Tel = customer.ContactPerson1Tel.Trim();
            customer.ContactPerson2 = customer.ContactPerson2.Trim();
            customer.ContactPerson2Phone1 = customer.ContactPerson2Phone1.Trim();
            customer.ContactPerson2Phone2 = customer.ContactPerson2Phone2.Trim();
            customer.ContactPerson2Tel = customer.ContactPerson2Tel.Trim();
            customer.Fax = customer.Fax.Trim();
            customer.FinancialAffairs = customer.FinancialAffairs.Trim();
            customer.FinancialAffairsPhone1 = customer.FinancialAffairsPhone1.Trim();
            customer.FinancialAffairsPhone2 = customer.FinancialAffairsPhone2.Trim();
            customer.FinancialAffairsTel = customer.FinancialAffairsTel.Trim();
            customer.Name = customer.Name.Trim();
            customer.Remark = customer.Remark.Trim();

            if (customer.Name == string.Empty)
                throw new BusinessException(VerificationText.请输入客户名称);
            if (customer.Salesman == null)
                throw new BusinessException(VerificationText.请输入业务员);

            foreach (Contract.Passenger passenger in customer.PassengerList)
            {
                checkPassenger(passenger);
            }
        }

        private void checkPassenger(Contract.Passenger passenger)
        {
            passenger.CName = passenger.CName.Trim();
            passenger.EName = passenger.EName.Trim();
            passenger.FlightCard1 = passenger.FlightCard1.Trim();
            passenger.FlightCard2 = passenger.FlightCard2.Trim();
            passenger.FlightCard3 = passenger.FlightCard3.Trim();
            passenger.IDCardNr1 = passenger.IDCardNr1.Trim();
            passenger.IDCardNr2 = passenger.IDCardNr2.Trim();
            passenger.IDCardType1 = passenger.IDCardType1.Trim();
            passenger.IDCardType2 = passenger.IDCardType2.Trim();
            passenger.Nation = passenger.Nation.Trim();
            passenger.Sex = passenger.Sex.Trim();
            passenger.Tel1 = passenger.Tel1.Trim();
            passenger.Tel2 = passenger.Tel2.Trim();

            if (passenger.CName == string.Empty && passenger.EName == string.Empty)
                throw new BusinessException(VerificationText.请输入乘客名称);
            //if (passenger.Sex == string.Empty)
            //    throw new BusinessException(VerificationText.请输入乘客性别);
            //if (passenger.Nation == string.Empty)
            //    throw new BusinessException(VerificationText.请输入乘客国籍);
        }

        public void UpdateCustomer(Contract.Customer customer)
        {
            checkCustomer(customer);



            Customer oldCustomer = (from c in entities.Customer
                                    where c.ID == customer.ID
                                    select c).SingleOrDefault();
            if (oldCustomer == null)
            {
                NewCustomer(customer);
                return;
            }

            oldCustomer.Name = customer.Name;
            oldCustomer.Address = customer.Address;
            oldCustomer.ContactPerson1 = customer.ContactPerson1;
            oldCustomer.ContactPerson2 = customer.ContactPerson2;
            oldCustomer.ContactPerson1Phone1 = customer.ContactPerson1Phone1;
            oldCustomer.ContactPerson1Phone2 = customer.ContactPerson1Phone2;
            oldCustomer.ContactPerson2Phone1 = customer.ContactPerson2Phone1;
            oldCustomer.ContactPerson2Phone2 = customer.ContactPerson2Phone2;
            oldCustomer.ContactPerson1Tel = customer.ContactPerson1Tel;
            oldCustomer.ContactPerson2Tel = customer.ContactPerson2Tel;
            oldCustomer.Fax = customer.Fax;
            oldCustomer.FinancialAffairs = customer.FinancialAffairs;
            oldCustomer.FinancialAffairsPhone1 = customer.FinancialAffairsPhone1;
            oldCustomer.FinancialAffairsPhone2 = customer.FinancialAffairsPhone2;
            oldCustomer.FinancialAffairsTel = customer.FinancialAffairsTel;
            oldCustomer.FlightIntergralRate = customer.FlightIntergralRate;
            oldCustomer.Remark = customer.Remark;
            oldCustomer.Amount = customer.Amount;
            oldCustomer.HotelIntergralRate = customer.HotelIntergralRate;
            oldCustomer.SalesmanID = customer.Salesman.ID;
            oldCustomer.UpdateTime = DateTime.Now;
            oldCustomer.Intergral = customer.Intergral;
            //if (customer.HotelIntergralList.Count != 0)
            //    oldCustomer.HotelIntergralRate = null;

            if (customer.WebUser != null && customer.WebUser.ID != oldCustomer.WebUserID)
            {
                WebUser oldWebUser = (from wu in entities.WebUser
                                      where wu.ID == customer.WebUser.ID
                                      select wu).SingleOrDefault();
                if (oldWebUser == null)
                {
                    WebUser newWebUser = new WebUser()
                    {
                        ID = customer.WebUser.ID,
                        Name = customer.WebUser.Name,
                        Password = customer.WebUser.Password,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        CreateParty = "程序"
                    };
                    entities.AddToWebUser(newWebUser);
                    oldCustomer.WebUserID = newWebUser.ID;
                }
                else
                {
                    oldCustomer.WebUserID = oldWebUser.ID;
                }
            }

            foreach (Contract.CustomerHotelIntergralRate customerHotelIntergralRate in customer.HotelIntergralList)
            {
                CustomerHotelIntergralRate chir = (from ch in entities.CustomerHotelIntergralRate
                                                   where ch.ID == customerHotelIntergralRate.ID
                                                   select ch).SingleOrDefault();
                if (chir != null)
                {
                    chir.Intergral = customerHotelIntergralRate.Intergral;
                }
                else
                {
                    chir = new CustomerHotelIntergralRate()
                    {
                        ID = customerHotelIntergralRate.ID,
                        Intergral = customerHotelIntergralRate.Intergral,
                        HotelLevelID = customerHotelIntergralRate.HotelLevel.ID,
                        CustomerID = customer.ID
                    };
                    entities.AddToCustomerHotelIntergralRate(chir);
                }
            }

            foreach (Contract.Passenger passenger in customer.PassengerList)
            {
                Passenger oldPassenger = (from p in entities.Passenger
                                          where p.ID == passenger.ID
                                          select p).SingleOrDefault();
                if (oldPassenger != null)
                {
                    oldPassenger.BirthDay = passenger.BirthDay;
                    oldPassenger.CName = passenger.CName;
                    oldPassenger.Effective = passenger.Effective;
                    oldPassenger.EName = passenger.EName;
                    oldPassenger.FlightCard1 = passenger.FlightCard1;
                    oldPassenger.FlightCard2 = passenger.FlightCard2;
                    oldPassenger.FlightCard3 = passenger.FlightCard3;
                    oldPassenger.IDCardNr1 = passenger.IDCardNr1;
                    oldPassenger.IDCardNr2 = passenger.IDCardNr2;
                    oldPassenger.IDCardType1 = passenger.IDCardType1;
                    oldPassenger.IDCardType2 = passenger.IDCardType2;
                    oldPassenger.IDCardEffective1 = passenger.IDCardEffective1;
                    oldPassenger.IDCardEffective2 = passenger.IDCardEffective2;
                    oldPassenger.Nation = passenger.Nation;
                    oldPassenger.Sex = passenger.Sex;
                    oldPassenger.Tel1 = passenger.Tel1;
                    oldPassenger.Tel2 = passenger.Tel2;
                }
                else
                {
                    Passenger newPassenger = new Passenger()
                    {
                        ID = passenger.ID,
                        BirthDay = passenger.BirthDay,
                        CName = passenger.CName,
                        Effective = passenger.Effective,
                        EName = passenger.EName,
                        FlightCard1 = passenger.FlightCard1,
                        FlightCard2 = passenger.FlightCard2,
                        FlightCard3 = passenger.FlightCard3,
                        IDCardNr1 = passenger.IDCardNr1,
                        IDCardNr2 = passenger.IDCardNr2,
                        IDCardType1 = passenger.IDCardType1,
                        IDCardType2 = passenger.IDCardType2,
                        IDCardEffective1 = passenger.IDCardEffective1,
                        IDCardEffective2 = passenger.IDCardEffective2,
                        Nation = passenger.Nation,
                        Sex = passenger.Sex,
                        Tel1 = passenger.Tel1,
                        Tel2 = passenger.Tel2,
                        CustomerID = customer.ID,
                    };
                    entities.AddToPassenger(newPassenger);
                }
            }

            entities.SaveChanges();
        }

        public void DeleteCustomer(Contract.Customer customer)
        {
            Customer oldCustomer = (from c in entities.Customer
                                    where c.ID == customer.ID
                                    select c).SingleOrDefault();
            if (oldCustomer == null)
                throw new BusinessException(CommonFail.客户不存在);

            if (oldCustomer.Used)
                throw new BusinessException(CommonFail.客户已被使用);

            foreach (Passenger passenger in oldCustomer.Passenger.ToList())
                entities.DeleteObject(passenger);

            entities.DeleteObject(oldCustomer);

            entities.SaveChanges();

        }

        public List<Contract.RVendor> GetAllVendor()
        {
            var list = (from v in entities.Vendor
                        where v.Nr.StartsWith("V")
                        orderby v.Nr
                        select new Contract.RVendor()
                        {
                            ID = v.ID,
                            Effective = v.Effective,
                            Name = v.Name.Trim(),
                            Nr = v.Nr.Trim(),
                            Remark = v.Remark,
                        }).ToList();

            foreach (Contract.RVendor vendor in list)
                vendor.ProjectList = (from vp in entities.VendorProject
                                      join p in entities.Project on vp.ProjectID equals p.ID
                                      where vp.VendorID == vendor.ID
                                      select p.Name.Trim()).ToList();

            return list;

        }

        public Contract.RVendor GetRVendorByID(Guid id)
        {
            Contract.RVendor vendor =
                (from v in entities.Vendor
                 where v.ID == id
                 orderby v.Nr
                 select new Contract.RVendor()
                 {
                     ID = v.ID,
                     Effective = v.Effective,
                     Name = v.Name.Trim(),
                     Nr = v.Nr.Trim(),
                     Remark = v.Remark,
                 }).SingleOrDefault();

            vendor.ProjectList = (from vp in entities.VendorProject
                                  join p in entities.Project on vp.ProjectID equals p.ID
                                  where vp.VendorID == vendor.ID
                                  select p.Name.Trim()).ToList();

            return vendor;
        }

        public List<Contract.RVendor> GetVendorByProject(Contract.Project project)
        {

            return (from v in entities.Vendor
                    where (from vp in entities.VendorProject
                           where vp.ProjectID == project.ID
                           select vp.VendorID).Contains(v.ID)
                    orderby v.Nr
                    select new Contract.RVendor()
                    {
                        ID = v.ID,
                        Effective = v.Effective,
                        Name = v.Name.Trim(),
                        Nr = v.Nr.Trim(),
                        Remark = v.Remark,
                    }).ToList();
        }

        public List<Contract.RVendor> GetAllHotelVendor()
        {

            Guid insuranceProjectID = (from p in _ProjectList
                                       where p.Name == "酒店"
                                       select p.ID).Single();

            return (from v in entities.Vendor
                    where (from vp in entities.VendorProject
                           where vp.ProjectID == insuranceProjectID
                           select vp.VendorID).Contains(v.ID)
                    orderby v.Nr
                    select new Contract.RVendor()
                    {
                        ID = v.ID,
                        Effective = v.Effective,
                        Name = v.Name.Trim(),
                        Nr = v.Nr.Trim(),
                        Remark = v.Remark,
                    }).ToList();
        }

        public List<Contract.RVendor> GetAllTrainVendor()
        {

            Guid insuranceProjectID = (from p in _ProjectList
                                       where p.Name == "火车票"
                                       select p.ID).Single();

            return (from v in entities.Vendor
                    where (from vp in entities.VendorProject
                           where vp.ProjectID == insuranceProjectID
                           select vp.VendorID).Contains(v.ID)
                    orderby v.Nr
                    select new Contract.RVendor()
                    {
                        ID = v.ID,
                        Effective = v.Effective,
                        Name = v.Name.Trim(),
                        Nr = v.Nr.Trim(),
                        Remark = v.Remark,
                    }).ToList();
        }

        public List<Contract.RVendor> GetAllFlightVendor()
        {

            Guid insuranceProjectID = (from p in _ProjectList
                                       where p.Name == "飞机票"
                                       select p.ID).Single();

            return (from v in entities.Vendor
                    where (from vp in entities.VendorProject
                           where vp.ProjectID == insuranceProjectID
                           select vp.VendorID).Contains(v.ID)
                    orderby v.Nr
                    select new Contract.RVendor()
                    {
                        ID = v.ID,
                        Effective = v.Effective,
                        Name = v.Name.Trim(),
                        Nr = v.Nr.Trim(),
                        Remark = v.Remark,
                    }).ToList();
        }

        public List<Contract.RVendor> GetAllInsuranceVendor()
        {

            Guid insuranceProjectID = (from p in _ProjectList
                                       where p.Name == "保险"
                                       select p.ID).Single();

            return (from v in entities.Vendor
                    where (from vp in entities.VendorProject
                           where vp.ProjectID == insuranceProjectID
                           select vp.VendorID).Contains(v.ID)
                    orderby v.Nr
                    select new Contract.RVendor()
                    {
                        ID = v.ID,
                        Effective = v.Effective,
                        Name = v.Name.Trim(),
                        Nr = v.Nr.Trim(),
                        Remark = v.Remark,
                    }).ToList();
        }

        public Contract.Vendor GetVendorByID(Guid id)
        {

            Contract.Vendor vendor =
                (from v in entities.Vendor
                 where v.ID == id
                 orderby v.Nr
                 select new Contract.Vendor()
                 {
                     ID = v.ID,
                     Address = v.Address.Trim(),
                     ContactPerson1 = v.ContactPerson1.Trim(),
                     ContactPerson1Tel1 = v.ContactPerson1Tel1.Trim(),
                     ContactPerson1Tel2 = v.ContactPerson1Tel2.Trim(),
                     ContactPerson2 = v.ContactPerson2.Trim(),
                     ContactPerson2Tel1 = v.ContactPerson2Tel1.Trim(),
                     ContactPerson2Tel2 = v.ContactPerson2Tel2.Trim(),
                     Effective = v.Effective,
                     Fax1 = v.Fax1.Trim(),
                     Fax2 = v.Fax2.Trim(),
                     Financial = v.Financial.Trim(),
                     FinancialTel1 = v.FinancialTel1.Trim(),
                     FinancialTel2 = v.FinancialTel2.Trim(),
                     Name = v.Name.Trim(),
                     Nr = v.Nr.Trim(),
                     Remark = v.Remark.Trim(),
                     Tel1 = v.Tel1.Trim(),
                     Tel2 = v.Tel2.Trim(),
                     Tel3 = v.Tel3.Trim(),
                     Tel4 = v.Tel4.Trim(),
                     Tel5 = v.Tel5.Trim(),
                     Tel6 = v.Tel6.Trim(),

                 }).SingleOrDefault();

            vendor.ProjectList = (from vp in entities.VendorProject
                                  join p in entities.Project on vp.ProjectID equals p.ID
                                  where vp.VendorID == vendor.ID
                                  select new Contract.Project()
                                  {
                                      ID = p.ID,
                                      Effective = p.Effective,
                                      Name = p.Name.Trim(),
                                      ReportStyle = p.ReportStyle
                                  }).ToList();

            return vendor;
        }

        public string NewVendor(Contract.Vendor vendor)
        {
            checkVendor(vendor);


            Vendor oldVendor = (from v in entities.Vendor
                                where v.Name == vendor.Name
                                select v).SingleOrDefault();
            if (oldVendor != null)
                throw new BusinessException(CommonFail.供应商已存在);

            Vendor newVendor = new Vendor()
            {
                ID = vendor.ID,
                Address = vendor.Address,
                ContactPerson1 = vendor.ContactPerson1,
                ContactPerson1Tel1 = vendor.ContactPerson1Tel1,
                ContactPerson1Tel2 = vendor.ContactPerson1Tel2,
                ContactPerson2 = vendor.ContactPerson2,
                ContactPerson2Tel1 = vendor.ContactPerson2Tel1,
                ContactPerson2Tel2 = vendor.ContactPerson2Tel2,
                Effective = vendor.Effective,
                Fax1 = vendor.Fax1,
                Fax2 = vendor.Fax2,
                Financial = vendor.Financial,
                FinancialTel1 = vendor.FinancialTel1,
                FinancialTel2 = vendor.FinancialTel2,
                Name = vendor.Name,
                Nr = new BaseBL().GetNewNr("Vendor"),
                Remark = vendor.Remark,
                Tel1 = vendor.Tel1,
                Tel2 = vendor.Tel2,
                Tel3 = vendor.Tel3,
                Tel4 = vendor.Tel4,
                Tel5 = vendor.Tel5,
                Tel6 = vendor.Tel6,
                Area = string.Empty,
                Type = string.Empty,
            };
            entities.AddToVendor(newVendor);

            foreach (Contract.Project project in vendor.ProjectList)
            {
                VendorProject vendorProject = new VendorProject();
                vendorProject.ID = Guid.NewGuid();
                vendorProject.ProjectID = project.ID;
                vendorProject.VendorID = vendor.ID;

                entities.AddToVendorProject(vendorProject);
            }

            entities.SaveChanges();

            return newVendor.Nr;
        }

        private void checkVendor(Contract.Vendor vendor)
        {
            vendor.Address = vendor.Address.Trim();
            vendor.ContactPerson1 = vendor.ContactPerson1.Trim();
            vendor.ContactPerson1Tel1 = vendor.ContactPerson1Tel1.Trim();
            vendor.ContactPerson1Tel2 = vendor.ContactPerson1Tel2.Trim();
            vendor.ContactPerson2 = vendor.ContactPerson2.Trim();
            vendor.ContactPerson2Tel1 = vendor.ContactPerson2Tel1.Trim();
            vendor.ContactPerson2Tel2 = vendor.ContactPerson2Tel2.Trim();
            vendor.Fax1 = vendor.Fax1.Trim();
            vendor.Fax2 = vendor.Fax2.Trim();
            vendor.Financial = vendor.Financial.Trim();
            vendor.FinancialTel1 = vendor.FinancialTel1.Trim();
            vendor.FinancialTel2 = vendor.FinancialTel2.Trim();
            vendor.Name = vendor.Name.Trim();
            vendor.Remark = vendor.Remark.Trim();
            vendor.Tel1 = vendor.Tel1.Trim();
            vendor.Tel2 = vendor.Tel2.Trim();
            vendor.Tel3 = vendor.Tel3.Trim();
            vendor.Tel4 = vendor.Tel4.Trim();
            vendor.Tel5 = vendor.Tel5.Trim();
            vendor.Tel6 = vendor.Tel6.Trim();

            if (vendor.Name == string.Empty)
                throw new BusinessException(VerificationText.请输入供应商名称);
            if (vendor.ProjectList.Count == 0)
                throw new BusinessException(VerificationText.请输入供应商类型);
        }

        public void UpdateVendor(Contract.Vendor vendor)
        {

            Vendor oldVendor = (from v in entities.Vendor
                                where v.ID == vendor.ID
                                select v).SingleOrDefault();
            if (oldVendor == null)
            {
                NewVendor(vendor);
                return;
            }


            oldVendor.ID = vendor.ID;
            oldVendor.Address = vendor.Address;
            oldVendor.ContactPerson1 = vendor.ContactPerson1;
            oldVendor.ContactPerson1Tel1 = vendor.ContactPerson1Tel1;
            oldVendor.ContactPerson1Tel2 = vendor.ContactPerson1Tel2;
            oldVendor.ContactPerson2 = vendor.ContactPerson2;
            oldVendor.ContactPerson2Tel1 = vendor.ContactPerson2Tel1;
            oldVendor.ContactPerson2Tel2 = vendor.ContactPerson2Tel2;
            oldVendor.Effective = vendor.Effective;
            oldVendor.Fax1 = vendor.Fax1;
            oldVendor.Fax2 = vendor.Fax2;
            oldVendor.Financial = vendor.Financial;
            oldVendor.FinancialTel1 = vendor.FinancialTel1;
            oldVendor.FinancialTel2 = vendor.FinancialTel2;
            oldVendor.Remark = vendor.Remark;
            oldVendor.Tel1 = vendor.Tel1;
            oldVendor.Tel2 = vendor.Tel2;
            oldVendor.Tel3 = vendor.Tel3;
            oldVendor.Tel4 = vendor.Tel4;
            oldVendor.Tel5 = vendor.Tel5;
            oldVendor.Tel6 = vendor.Tel6;
            oldVendor.Type = string.Empty;
            oldVendor.Area = string.Empty;

            foreach (VendorProject vendorProject in oldVendor.VendorProject.ToArray())
                entities.DeleteObject(vendorProject);

            foreach (Contract.Project project in vendor.ProjectList)
            {
                VendorProject vendorProject = new VendorProject();
                vendorProject.ID = Guid.NewGuid();
                vendorProject.ProjectID = project.ID;
                vendorProject.VendorID = vendor.ID;

                entities.AddToVendorProject(vendorProject);
            }

            entities.SaveChanges();
        }

        public List<Contract.InsurancePolicy> GetAllInsurancePolicy()
        {
            var list = (from ip in entities.InsurancePolicy
                        orderby ip.Ref descending
                        select new Contract.InsurancePolicy()
                        {
                            ID = ip.ID,
                            BasePrice = ip.BasePrice,
                            Currency = new Contract.Currency() { ID = ip.CurrencyID },
                            ListPrice = ip.ListPrice,
                            Ref = ip.Ref.Trim(),
                            Type = ip.Type.Trim(),
                            Status = ip.Status.Trim(),
                            Vendor = new Contract.RVendor() { ID = ip.VendorID },
                            Passenger = ip.FlightOrderDetail.Passenger.CName.Trim(),
                            UsedDate = ip.UsedDate
                        }).ToList();

            foreach (Contract.InsurancePolicy insurancePolicy in list)
            {
                insurancePolicy.Currency = (from c in entities.Currency
                                            where c.ID == insurancePolicy.Currency.ID
                                            select new Contract.Currency()
                                            {
                                                ID = c.ID,
                                                Name = c.Name.Trim(),
                                                Code = c.Code.Trim(),
                                            }).FirstOrDefault();
                insurancePolicy.Vendor = (from v in entities.Vendor
                                          where v.ID == insurancePolicy.Vendor.ID
                                          select new Contract.RVendor()
                                          {
                                              ID = v.ID,
                                              Name = v.Name.Trim(),
                                              Nr = v.Nr.Trim()
                                          }).FirstOrDefault();
            }

            return list;
        }

        public List<Contract.InsurancePolicy> GetAllAvailableInsurancePolicy()
        {

            var list = (from ip in entities.InsurancePolicy
                        where ip.Status != "已用" && ip.Status != "已寄回" && ip.Status != "不可用"
                        orderby ip.Ref
                        select new Contract.InsurancePolicy()
                        {
                            ID = ip.ID,
                            BasePrice = ip.BasePrice,
                            Currency = new Contract.Currency() { ID = ip.CurrencyID },
                            ListPrice = ip.ListPrice,
                            Ref = ip.Ref.Trim(),
                            Type = ip.Type.Trim(),
                            Status = ip.Status.Trim(),
                            Vendor = new Contract.RVendor() { ID = ip.VendorID }
                        }).ToList();

            foreach (Contract.InsurancePolicy insurancePolicy in list)
            {
                insurancePolicy.Currency = (from c in entities.Currency
                                            where c.ID == insurancePolicy.Currency.ID
                                            select new Contract.Currency()
                                            {
                                                ID = c.ID,
                                                Name = c.Name.Trim(),
                                                Code = c.Code.Trim(),
                                            }).FirstOrDefault();
                insurancePolicy.Vendor = (from v in entities.Vendor
                                          where v.ID == insurancePolicy.Vendor.ID
                                          select new Contract.RVendor()
                                          {
                                              ID = v.ID,
                                              Name = v.Name.Trim(),
                                              Nr = v.Nr.Trim()
                                          }).FirstOrDefault();
            }

            return list;
        }

        public void NewInsurancePolicy(Contract.NewInsurancePolicy _newInsurancePolicy)
        {
            if (_newInsurancePolicy.PaymentType.Trim() != "现金" && _newInsurancePolicy.BankAccount == null)
                throw new BusinessException(VerificationText.请输入银行账户);
            if (_newInsurancePolicy.InsurancePolicyList.Count == 0)
                throw new BusinessException(VerificationText.请输入保险单号);

            Stopwatch sw = new Stopwatch();
            sw.Start();

            //List<string> duplicateRefList = new List<string>();
            //foreach (Contract.InsurancePolicy insurancePolicy in _newInsurancePolicy.InsurancePolicyList)
            //{
            //    checkInsurancePolicy(insurancePolicy);

            //    if (entities.InsurancePolicy.Any(ip => ip.Ref == insurancePolicy.Ref))
            //        duplicateRefList.Add(insurancePolicy.Ref);
            //}

            //if (duplicateRefList.Count != 0)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    foreach (string _ref in duplicateRefList)
            //        sb.AppendLine(_ref);

            //    Contract.FailValue failValue = new Contract.FailValue();
            //    failValue.Name = "DuplicateRefList";
            //    failValue.Value = sb.ToString();

            //    throw new BusinessException(CommonFail.保险单号重复, failValue);
            //}

            decimal amount = 0;
            foreach (Contract.InsurancePolicy insurancePolicy in _newInsurancePolicy.InsurancePolicyList)
            {
                InsurancePolicy newInsurancePolicy = new InsurancePolicy()
                {
                    ID = insurancePolicy.ID,
                    BasePrice = insurancePolicy.BasePrice,
                    CurrencyID = insurancePolicy.Currency.ID,
                    ListPrice = insurancePolicy.ListPrice,
                    Status = insurancePolicy.Status,
                    VendorID = insurancePolicy.Vendor.ID,
                    Ref = insurancePolicy.Ref,
                    Type = insurancePolicy.Type,
                    VendorStatus = "已付款"
                };

                amount += insurancePolicy.BasePrice;

                entities.AddToInsurancePolicy(newInsurancePolicy);
            }

            VendorSettlement vendorSettlemnet = new VendorSettlement();
            if (_newInsurancePolicy.BankAccount != null)
            {
                vendorSettlemnet.BankAccountID = _newInsurancePolicy.BankAccount.ID;
                BankAccount bankAccount = (from b in entities.BankAccount
                                           where b.ID == _newInsurancePolicy.BankAccount.ID
                                           select b).Single();
                bankAccount.Amount -= amount;
                if (bankAccount.Amount < 0 && !bankAccount.CanNegative)
                    throw new BusinessException(BusinessFail.余额不足);
            }
            vendorSettlemnet.ID = Guid.NewGuid();
            vendorSettlemnet.CurrencyID = new BaseBL().GetCNYCurrency().ID;
            vendorSettlemnet.ExchangeRate = 1;
            vendorSettlemnet.PayType = _newInsurancePolicy.PaymentType.Trim();
            vendorSettlemnet.PostingDate = DateTime.Now;
            vendorSettlemnet.Type = "保险单";
            vendorSettlemnet.Ref = string.Format("{0} - {1}", _newInsurancePolicy.InsurancePolicyList[0].Ref, _newInsurancePolicy.InsurancePolicyList[_newInsurancePolicy.InsurancePolicyList.Count - 1].Ref);
            //vendorSettlemnet.Ref = string.Format("保险单共{0}张", _newInsurancePolicy.InsurancePolicyList.Count);
            vendorSettlemnet.Remark = string.Empty;
            vendorSettlemnet.Amount = amount;
            vendorSettlemnet.SourceID = Guid.Empty;
            vendorSettlemnet.VendorID = _newInsurancePolicy.InsurancePolicyList[0].Vendor.ID;

            entities.AddToVendorSettlement(vendorSettlemnet);

            entities.SaveChanges();

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
        }

        private void checkInsurancePolicy(Contract.InsurancePolicy insurancePolicy)
        {
            insurancePolicy.Ref = insurancePolicy.Ref.Trim();
            insurancePolicy.Remark = insurancePolicy.Remark.Trim();
            insurancePolicy.Status = insurancePolicy.Status.Trim();
            insurancePolicy.Type = insurancePolicy.Type.Trim();

            if (insurancePolicy.Type == string.Empty)
                throw new BusinessException(VerificationText.请输入保险单类型);
            if (insurancePolicy.Vendor == null)
                throw new BusinessException(VerificationText.请输入供应商);
        }

        public void UpdateInsurancePolicy(Contract.InsurancePolicy insurancePolicy)
        {
            checkInsurancePolicy(insurancePolicy);


            InsurancePolicy oldInsurancePolicy =
                (from ip in entities.InsurancePolicy
                 where ip.ID == insurancePolicy.ID
                 select ip).SingleOrDefault();
            if (oldInsurancePolicy == null)
                throw new BusinessException(CommonFail.保险单不存在);

            oldInsurancePolicy.BasePrice = insurancePolicy.BasePrice;
            oldInsurancePolicy.ListPrice = insurancePolicy.ListPrice;
            oldInsurancePolicy.Status = insurancePolicy.Status;
            oldInsurancePolicy.Type = insurancePolicy.Type;

            entities.SaveChanges();
        }

        public Contract.InsurancePolicy ReturnInsurancePolicy(Contract.InsurancePolicy oldInsurancePolicy, string newRef)
        {
            var oldIP = (from ip in entities.InsurancePolicy
                         where ip.ID == oldInsurancePolicy.ID
                         select ip).SingleOrDefault();
            oldIP.Status = "已寄回";

            //if (entities.InsurancePolicy.Any(ip => ip.Ref == newRef.Trim()))
            //    throw new BusinessException(CommonFail.保险单号重复);

            //InsurancePolicy newIP = new InsurancePolicy();
            //newIP.ID = Guid.NewGuid();
            //newIP.BasePrice = oldIP.BasePrice;
            //newIP.CurrencyID = oldIP.CurrencyID;
            //newIP.ListPrice = oldIP.ListPrice;
            //newIP.Type = oldIP.Type;
            //newIP.Ref = newRef.Trim();
            //newIP.Status = "可用";
            //newIP.VendorID = oldIP.VendorID;
            //newIP.VendorStatus = "已付款";

            //entities.AddToInsurancePolicy(newIP);

            entities.SaveChanges();

            //Contract.InsurancePolicy cInsurancePolicy = new Contract.InsurancePolicy();
            //cInsurancePolicy.ID = newIP.ID;
            //cInsurancePolicy.BasePrice = newIP.BasePrice;
            //cInsurancePolicy.Currency = oldInsurancePolicy.Currency;
            //cInsurancePolicy.ListPrice = newIP.ListPrice;
            //cInsurancePolicy.Vendor = oldInsurancePolicy.Vendor;
            //cInsurancePolicy.Type = newIP.Type;
            //cInsurancePolicy.Ref = newIP.Ref;
            //cInsurancePolicy.Status = newIP.Status;

            return null;
        }

        public Contract.JourneyOrder ReturnJourneyOrder(Contract.JourneyOrder oldJourneyOrder, string newRef)
        {
            var oldIP = (from ip in entities.JourneyOrder
                         where ip.ID == oldJourneyOrder.ID
                         select ip).SingleOrDefault();
            oldIP.Status = "已寄回";

            //if (entities.JourneyOrder.Any(ip => ip.Ref == newRef.Trim()))
            //    throw new BusinessException(CommonFail.行程单号重复);

            //JourneyOrder newIP = new JourneyOrder();
            //newIP.ID = Guid.NewGuid();
            //newIP.Type = oldIP.Type;
            //newIP.Ref = newRef.Trim();
            //newIP.Status = "可用";
            //entities.AddToJourneyOrder(newIP);

            entities.SaveChanges();

            //Contract.JourneyOrder cInsurancePolicy = new Contract.JourneyOrder();
            //cInsurancePolicy.ID = newIP.ID;
            //cInsurancePolicy.Type = newIP.Type;
            //cInsurancePolicy.Ref = newIP.Ref;
            //cInsurancePolicy.Status = newIP.Status;

            return null;
        }

        public Contract.InsurancePolicy GetAvailableInsurancePolicy(Contract.RVendor vendor, string type)
        {

            InsurancePolicy insurancePolicy =
                (from ip in entities.InsurancePolicy
                 where ip.Status.Trim() == "可用" && ip.Type.Trim() == type && ip.VendorID == vendor.ID
                 orderby ip.Ref
                 select ip).FirstOrDefault();

            if (insurancePolicy == null)
                throw new BusinessException(CommonFail.没有可用的保险单);

            Contract.InsurancePolicy cInsyrancePolicy =
                new Contract.InsurancePolicy()
                 {
                     ID = insurancePolicy.ID,
                     BasePrice = insurancePolicy.BasePrice,
                     Currency = (from c in entities.Currency
                                 where c.ID == insurancePolicy.CurrencyID
                                 select new Contract.Currency()
                                 {
                                     ID = c.ID,
                                     Name = c.Name.Trim(),
                                     Code = c.Code.Trim(),
                                 }).FirstOrDefault(),
                     ListPrice = insurancePolicy.ListPrice,
                     Ref = insurancePolicy.Ref.Trim(),
                     Type = insurancePolicy.Type.Trim(),
                     Status = insurancePolicy.Status.Trim(),
                 };

            insurancePolicy.Status = "暂用";
            entities.SaveChanges();

            return cInsyrancePolicy;
        }

        public List<string> GetInsurancePolicyTypeList()
        {

            return (from ip in entities.InsurancePolicy
                    where ip.Status == "可用"
                    group ip by ip.Type into g
                    select g.Key
                    ).ToList();
        }

        public List<Contract.JourneyOrder> GetAllJourneyOrder()
        {

            return (from ip in entities.JourneyOrder
                    orderby ip.Ref descending
                    select new Contract.JourneyOrder()
                    {
                        ID = ip.ID,
                        Ref = ip.Ref.Trim(),
                        Type = ip.Type.Trim(),
                        Status = ip.Status.Trim(),
                        TicketNo = ip.FlightOrderDetail.TicketNo.Trim(),
                        Passenger = ip.FlightOrderDetail.Passenger.CName.Trim() + "/" + ip.FlightOrderDetail.Passenger.EName.Trim(),
                        UsedDate = ip.UsedDate
                    }).ToList();
        }

        public List<Contract.JourneyOrder> GetAllAvailableJourneyOrder()
        {

            return (from ip in entities.JourneyOrder
                    where ip.Status != "已用" && ip.Status != "已寄回" && ip.Status != "作废"
                    orderby ip.Ref
                    select new Contract.JourneyOrder()
                    {
                        ID = ip.ID,
                        Ref = ip.Ref.Trim(),
                        Type = ip.Type.Trim(),
                        Status = ip.Status.Trim(),
                    }).ToList();
        }

        public void NewJourneyOrder(List<Contract.JourneyOrder> journeyOrderList)
        {
            if (journeyOrderList.Count == 0)
                throw new BusinessException(VerificationText.请输入行程单号);

            //List<string> duplicateRefList = new List<string>();
            //foreach (Contract.JourneyOrder journeyOrder in journeyOrderList)
            //{
            //    checkJourneyOrder(journeyOrder);

            //    if (entities.JourneyOrder.Any(ip => ip.Ref == journeyOrder.Ref))
            //        duplicateRefList.Add(journeyOrder.Ref);
            //}

            //if (duplicateRefList.Count != 0)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    foreach (string _ref in duplicateRefList)
            //        sb.AppendLine(_ref);

            //    Contract.FailValue failValue = new Contract.FailValue();
            //    failValue.Name = "DuplicateRefList";
            //    failValue.Value = sb.ToString();

            //    throw new BusinessException(CommonFail.保险单号重复, failValue);
            //}

            foreach (Contract.JourneyOrder journeyOrder in journeyOrderList)
            {
                JourneyOrder newJourneyOrder = new JourneyOrder()
                {
                    ID = journeyOrder.ID,
                    Status = journeyOrder.Status,
                    Ref = journeyOrder.Ref,
                    Type = journeyOrder.Type,
                };

                entities.AddToJourneyOrder(newJourneyOrder);
            }

            entities.SaveChanges();
        }

        private void checkJourneyOrder(Contract.JourneyOrder journeyOrder)
        {
            journeyOrder.Ref = journeyOrder.Ref.Trim();
            journeyOrder.Status = journeyOrder.Status.Trim();
            journeyOrder.Type = journeyOrder.Type.Trim();

            if (journeyOrder.Type == string.Empty)
                throw new BusinessException(VerificationText.请输入行程单类型);
        }

        public void UpdateJourneyOrder(Contract.JourneyOrder journeyOrder)
        {

            JourneyOrder oldJourneyOrder =
                (from ip in entities.JourneyOrder
                 where ip.ID == journeyOrder.ID
                 select ip).SingleOrDefault();
            if (oldJourneyOrder == null)
                throw new BusinessException(CommonFail.行程单不存在);

            oldJourneyOrder.Status = journeyOrder.Status;
            oldJourneyOrder.Type = journeyOrder.Type;

            entities.SaveChanges();
        }

        public Contract.JourneyOrder GetAvailableJourneyOrder(string type)
        {

            JourneyOrder journeyOrder =
                (from ip in entities.JourneyOrder
                 where ip.Status == "可用" && ip.Type == type
                 orderby ip.Ref
                 select ip).FirstOrDefault();

            if (journeyOrder == null)
                throw new BusinessException(CommonFail.没有可用的行程单);

            Contract.JourneyOrder cJourneyOrder =
                new Contract.JourneyOrder()
                 {
                     ID = journeyOrder.ID,
                     Ref = journeyOrder.Ref.Trim(),
                     Type = journeyOrder.Type.Trim(),
                     Status = journeyOrder.Status.Trim(),
                 };

            journeyOrder.Status = "暂用";
            entities.SaveChanges();

            return cJourneyOrder;
        }

        public List<string> GetJourneyOrderTypeList()
        {

            return (from ip in entities.JourneyOrder
                    where ip.Status == "可用" || ip.Status == "暂用"
                    group ip by ip.Type into g
                    select g.Key
                    ).ToList();
        }

        public void UpdateTourVendor(Contract.TourVendor tourVendor)
        {
            Vendor dataTourVendor = (from tv in entities.Vendor
                                     where tv.ID == tourVendor.ID
                                     select tv).SingleOrDefault();

            if (dataTourVendor == null)
            {
                dataTourVendor = new Vendor();
                entities.AddToVendor(dataTourVendor);
                dataTourVendor.Nr = new BaseBL().GetNewNr("TourVendor");
            }

            dataTourVendor.ID = tourVendor.ID;
            dataTourVendor.Address = tourVendor.Address.Trim();
            dataTourVendor.ContactPerson1 = tourVendor.ContactPerson.Trim();
            dataTourVendor.ContactPerson1Tel1 = tourVendor.ContactPersonTel.Trim();
            dataTourVendor.Name = tourVendor.Name.Trim();
            dataTourVendor.Effective = tourVendor.Effective;
            dataTourVendor.Type = tourVendor.类别;
            dataTourVendor.Area = tourVendor.Area.Trim();
            dataTourVendor.Remark = tourVendor.Remark.Trim();

            dataTourVendor.ContactPerson1 = tourVendor.ContactPerson;
            dataTourVendor.ContactPerson1Tel1 = tourVendor.ContactPersonTel;
            dataTourVendor.ContactPerson1Tel2 = string.Empty;
            dataTourVendor.ContactPerson2 = string.Empty;
            dataTourVendor.ContactPerson2Tel1 = string.Empty;
            dataTourVendor.ContactPerson2Tel2 = string.Empty;

            dataTourVendor.Fax1 = string.Empty;
            dataTourVendor.Fax2 = string.Empty;
            dataTourVendor.Financial = string.Empty;
            dataTourVendor.FinancialTel1 = string.Empty;
            dataTourVendor.FinancialTel2 = string.Empty;

            dataTourVendor.Tel1 = string.Empty;
            dataTourVendor.Tel2 = string.Empty;
            dataTourVendor.Tel3 = string.Empty;
            dataTourVendor.Tel4 = string.Empty;
            dataTourVendor.Tel5 = string.Empty;
            dataTourVendor.Tel6 = string.Empty;

            foreach (VendorProject vendorProject in dataTourVendor.VendorProject.ToArray())
                entities.DeleteObject(vendorProject);

            foreach (Contract.Project project in tourVendor.ProjectList)
            {
                VendorProject vendorProject = new VendorProject();
                vendorProject.ID = Guid.NewGuid();
                vendorProject.ProjectID = project.ID;
                vendorProject.VendorID = dataTourVendor.ID;

                entities.AddToVendorProject(vendorProject);
            }

            for (int i = 0; i < tourVendor.TourList.Count; i++)
            {
                Contract.Tour tour = tourVendor.TourList[i];
                tour.Seq = i;

                Tour dataTour = (from t in entities.Tour
                                 where t.ID == tour.ID
                                 select t).SingleOrDefault();
                if (dataTour == null)
                {
                    dataTour = new Tour();
                    entities.AddToTour(dataTour);
                }

                dataTour.ID = tour.ID;
                dataTour.Name = tour.Name.Trim();
                dataTour.Price = tour.Price;
                dataTour.Remark = tour.Remark.Trim();
                dataTour.DepartDate = tour.DepartDate.Trim();
                dataTour.Travel = tour.Travel.Trim();
                dataTour.Feature = tour.Feature.Trim();
                dataTour.Seq = tour.Seq;
                dataTour.VendorID = tourVendor.ID;
            }

            foreach (Contract.TourVendorAttachment attachment in tourVendor.AttachmentList)
            {
                TourVendorAttachment tourVendorAttachment =
                    (from a in entities.TourVendorAttachment
                     where a.ID == attachment.ID
                     select a).SingleOrDefault();

                if (tourVendorAttachment == null)
                {
                    tourVendorAttachment = new TourVendorAttachment()
                    {
                        ID = attachment.ID,
                        Name = attachment.Name,
                        VendorID = dataTourVendor.ID,
                        File = attachment.File
                    };

                    entities.AddToTourVendorAttachment(tourVendorAttachment);
                }
            }

            entities.SaveChanges();
        }

        public List<Contract.RTourVendor> GetAllTourVendor()
        {
            return (from tv in entities.Vendor
                    where tv.Nr.StartsWith("TV")
                    orderby tv.Nr
                    select new Contract.RTourVendor()
                    {
                        ID = tv.ID,
                        Area = tv.Area.Trim(),
                        Name = tv.Name.Trim(),
                        Type = tv.Type.Trim()
                    }).ToList();
        }

        public List<Contract.RVendor> GetAllTourpartyVendor()
        {
            return (from tv in entities.Vendor
                    orderby tv.Nr
                    select new Contract.RVendor()
                    {
                        ID = tv.ID,
                        Address = tv.Address.Trim(),
                        Name = tv.Name.Trim(),
                        Nr = tv.Nr.Trim(),
                    }).ToList();
        }

        public Contract.TourVendor GetTourVendorByID(Guid id)
        {
            Contract.TourVendor tourVendor =
                (from tv in entities.Vendor
                 where tv.ID == id
                 select new Contract.TourVendor()
                 {
                     ID = tv.ID,
                     Address = tv.Address.Trim(),
                     ContactPerson = tv.ContactPerson1.Trim(),
                     ContactPersonTel = tv.ContactPerson1Tel1.Trim(),
                     Name = tv.Name.Trim(),
                     Nr = tv.Nr.Trim(),
                     Area = tv.Area.Trim(),
                     Type = tv.Type.Trim(),
                     Remark = tv.Remark.Trim()
                 }).Single();

            tourVendor.TourList =
                (from t in entities.Tour
                 where t.VendorID == tourVendor.ID
                 orderby t.Seq
                 select new Contract.Tour()
                 {
                     ID = t.ID,
                     Name = t.Name.Trim(),
                     Price = t.Price,
                     Remark = t.Remark.Trim(),
                     DepartDate = t.DepartDate.Trim(),
                     Travel = t.Travel.Trim(),
                     Feature = t.Feature.Trim(),
                     Seq = t.Seq
                 }).ToList();

            tourVendor.AttachmentList =
                (from a in entities.TourVendorAttachment
                 where a.VendorID == tourVendor.ID
                 orderby a.Name
                 select new Contract.TourVendorAttachment()
                 {
                     ID = a.ID,
                     Name = a.Name.Trim(),
                     File = a.File
                 }).ToList();

            tourVendor.ProjectList = (from vp in entities.VendorProject
                                      join p in entities.Project on vp.ProjectID equals p.ID
                                      where vp.VendorID == tourVendor.ID
                                      select new Contract.Project()
                                      {
                                          ID = p.ID,
                                          Effective = p.Effective,
                                          Name = p.Name.Trim(),
                                          ReportStyle = p.ReportStyle
                                      }).ToList();

            return tourVendor;
        }

        public List<Contract.STour> SearchTourByNameAndTravel(string name, string vendor, string type, string area, string feature, string travel)
        {
            name = name.Trim();
            feature = feature.Trim();
            type = type.Trim();
            area = area.Trim();
            vendor = vendor.Trim();
            travel = travel.Trim();

            return (from t in entities.Tour
                    join v in entities.Vendor on t.VendorID equals v.ID
                    where (name == string.Empty || t.Name.IndexOf(name) >= 0) &&
                           (feature == string.Empty || t.Feature.IndexOf(feature) >= 0) &&
                           (travel == string.Empty || t.Travel.IndexOf(travel) >= 0) &&
                           (vendor == string.Empty || v.Name.IndexOf(vendor) >= 0) &&
                           (area == string.Empty || v.Area.IndexOf(area) >= 0) &&
                           (type == string.Empty || (from vp in entities.VendorProject
                                                     where (from p in entities.Project
                                                            where p.Name.IndexOf(type) >= 0
                                                            select p.ID).Contains(vp.ProjectID)
                                                     select vp.VendorID).Contains(v.ID))
                    select new Contract.STour()
                    {
                        ID = t.ID,
                        ContactPerson = v.ContactPerson1.Trim(),
                        ContactPersonTel = v.ContactPerson1Tel1.Trim(),
                        DepartDate = t.DepartDate.Trim(),
                        Name = t.Name.Trim(),
                        Price = t.Price,
                        Remark = t.Remark.Trim(),
                        Travel = t.Travel.Trim(),
                        Vendor = v.Name.Trim(),
                        VendorID = v.ID
                    }).ToList();
        }

        public List<Contract.SearchTour> GetTourByName(string name)
        {
            return (from t in entities.Tour
                    join vt in entities.Vendor on t.VendorID equals vt.ID
                    where t.Name.IndexOf(name.Trim()) >= 0
                    select new Contract.SearchTour()
                    {
                        ID = t.ID,
                        ContactPerson = vt.ContactPerson1.Trim(),
                        ContactPersonTel = vt.ContactPerson1Tel1.Trim(),
                        Name = t.Name.Trim(),
                        Price = t.Price,
                        VendorID = vt.ID,
                        VendorName = vt.Name.Trim()
                    }).ToList();
        }

        public string UpdateTouringParty(Contract.TouringParty touringParty)
        {
            if (touringParty.Customer == null)
                throw new BusinessException(VerificationText.请输入客户);
            if (touringParty.SalesMan == null)
                throw new BusinessException(VerificationText.请输入业务员);
            if (touringParty.ProvideTicketUser == null)
                throw new BusinessException(VerificationText.请输入计调员);

            DateTime dateTime = DateTime.Now;

            TouringParty dataTouringParty = (from tp in entities.TouringParty
                                             where tp.ID == touringParty.ID
                                             select tp).SingleOrDefault();
            if (dataTouringParty == null)
            {
                dataTouringParty = new TouringParty();
                dataTouringParty.CreateTime = dateTime;
                dataTouringParty.Ref = new BaseBL().GetNewNr("TourParty");
                entities.AddToTouringParty(dataTouringParty);
            }

            dataTouringParty.AdultQty = touringParty.AdultQty;
            dataTouringParty.Address = touringParty.Address;
            dataTouringParty.AverageAdultPrice = Math.Round(touringParty.ActAverageAdultPrice, 2);
            dataTouringParty.AverageAdultVendorPrice = Math.Round(touringParty.AverageAdultVendorPrice, 2);
            dataTouringParty.AverageChildPrice = Math.Round(touringParty.ActAverageChildPrice, 2);
            dataTouringParty.AverageChildVendorPrice = Math.Round(touringParty.AverageChildVendorPrice, 2);
            dataTouringParty.ChildQty = touringParty.ChildQty;
            dataTouringParty.ContactPerson = touringParty.ContactPerson.Trim();
            dataTouringParty.ContactPersonTel = touringParty.ContactPersonTel.Trim();
            dataTouringParty.CustomerID = touringParty.Customer.ID;
            dataTouringParty.CustomerStatus = touringParty.CustomerStatus;
            dataTouringParty.Document = touringParty.Document;
            dataTouringParty.DocumentName = touringParty.DocumentName.Trim();
            dataTouringParty.ID = touringParty.ID;
            dataTouringParty.Name = touringParty.Name.Trim();
            dataTouringParty.OrderDate = touringParty.OrderDate.Value;
            dataTouringParty.OrderUserID = touringParty.OrderUser.ID;
            dataTouringParty.Remark = touringParty.Remark.Trim();
            dataTouringParty.TotalPrice = touringParty.TotalPrice;
            dataTouringParty.TotalVendorPrice = touringParty.TotalVendorPrice;
            dataTouringParty.TotalProfit = touringParty.TotalProfit;
            dataTouringParty.UpdateTime = dateTime;
            dataTouringParty.VendorStatus = touringParty.VendorStatus.Trim();
            dataTouringParty.SalesManID = touringParty.SalesMan.ID;
            dataTouringParty.ProvideTicketUserID = touringParty.ProvideTicketUser.ID;
            dataTouringParty.Status = touringParty.Status.Trim();
            dataTouringParty.IsShowOnWeb = touringParty.IsShowOnWeb;

            foreach (var tpi in dataTouringParty.TouringPartyItem.ToList())
                entities.DeleteObject(tpi);

            Contract.RVendor vendor = null;

            for (int i = 0; i < touringParty.Items.Count; i++)
            {
                Contract.TouringPartyItem touringPartyItem = touringParty.Items[i];
                if (touringPartyItem.Vendor != null)
                    vendor = touringPartyItem.Vendor;
                if (vendor == null)
                    throw new BusinessException(VerificationText.请输入供应商);

                TouringPartyItem dataTouringPartyItem = new TouringPartyItem();
                dataTouringPartyItem.CreateTime = dateTime;
                entities.AddToTouringPartyItem(dataTouringPartyItem);
                dataTouringPartyItem.ID = touringPartyItem.ID;
                dataTouringPartyItem.Name = touringPartyItem.Name.Trim();
                dataTouringPartyItem.Price = touringPartyItem.Price;
                dataTouringPartyItem.Qty = touringPartyItem.Qty;
                dataTouringPartyItem.Remark = touringPartyItem.Remark.Trim();
                dataTouringPartyItem.CalcType = touringPartyItem.CalcType.Trim();
                dataTouringPartyItem.VendorID = vendor.ID;
                dataTouringPartyItem.UM = touringPartyItem.UM.Trim();
                dataTouringPartyItem.Seq = i;
                dataTouringPartyItem.TotalPrice = touringPartyItem.TotalPrice;
                dataTouringPartyItem.TotalVendorPrice = touringPartyItem.TotalVendorPrice;
                dataTouringPartyItem.Profit = touringPartyItem.Profit;
                dataTouringPartyItem.TouringPartyID = touringParty.ID;
                dataTouringPartyItem.Type = touringPartyItem.Type.Trim();
                dataTouringPartyItem.UpdateTime = dateTime;
                dataTouringPartyItem.VendorPrice = touringPartyItem.VendorPrice;
            }

            entities.SaveChanges();

            return dataTouringParty.Ref;
        }

        public List<Contract.RTouringParty> GetAllTouringParty()
        {
            return (from tp in entities.TouringParty
                    orderby tp.Ref
                    select new Contract.RTouringParty()
                    {
                        ID = tp.ID,
                        Customer = (from c in entities.Customer
                                    where c.ID == tp.CustomerID
                                    select c.Name.Trim()).FirstOrDefault(),
                        Name = tp.Name.Trim(),
                        OrderDate = tp.OrderDate,
                        Ref = tp.Ref.Trim()
                    }).ToList();
        }

        public Contract.TouringParty GetTouringPartyByID(Guid id)
        {
            Contract.TouringParty touringParty =
                (from tp in entities.TouringParty
                 where tp.ID == id
                 select new Contract.TouringParty()
                 {
                     AdultQty = tp.AdultQty,
                     Address = tp.Address,
                     ChildQty = tp.ChildQty,
                     ContactPerson = tp.ContactPerson.Trim(),
                     ContactPersonTel = tp.ContactPersonTel.Trim(),
                     Customer = new Contract.Customer() { ID = tp.CustomerID },
                     CustomerStatus = tp.CustomerStatus.Trim(),
                     Document = tp.Document,
                     DocumentName = tp.DocumentName.Trim(),
                     ID = tp.ID,
                     Name = tp.Name.Trim(),
                     OrderDate = tp.OrderDate,
                     OrderUser = new Contract.User() { ID = tp.OrderUserID },
                     SalesMan = new Contract.User() { ID = tp.SalesManID },
                     ProvideTicketUser = new Contract.User() { ID = tp.ProvideTicketUserID },
                     Ref = tp.Ref.Trim(),
                     Remark = tp.Remark.Trim(),
                     VendorStatus = tp.VendorStatus.Trim(),
                     //TotalPrice = tp.TotalPrice,
                     ActAverageAdultPrice = tp.AverageAdultPrice,
                     ActAverageChildPrice = tp.AverageChildPrice,
                     Status = tp.Status.Trim(),
                     IsShowOnWeb = tp.IsShowOnWeb
                 }).SingleOrDefault();

            touringParty.Customer = GetCustomerByID(touringParty.Customer.ID);
            touringParty.OrderUser = new BaseBL().GetUserByID(touringParty.OrderUser.ID);
            touringParty.SalesMan = new BaseBL().GetUserByID(touringParty.SalesMan.ID);
            touringParty.ProvideTicketUser = new BaseBL().GetUserByID(touringParty.ProvideTicketUser.ID);
            touringParty.Items = (from tpi in entities.TouringPartyItem
                                  where tpi.TouringPartyID == touringParty.ID
                                  orderby tpi.Seq
                                  select new Contract.TouringPartyItem()
                                  {
                                      ID = tpi.ID,
                                      Name = tpi.Name.Trim(),
                                      Price = tpi.Price,
                                      Qty = tpi.Qty,
                                      Remark = tpi.Remark.Trim(),
                                      CalcType = tpi.CalcType.Trim(),
                                      Vendor = new Contract.RVendor() { ID = tpi.VendorID },
                                      Seq = tpi.Seq,
                                      TotalVendorPrice = tpi.TotalVendorPrice,
                                      Type = tpi.Type.Trim(),
                                      UM = tpi.UM.Trim(),
                                      VendorPrice = tpi.VendorPrice
                                  }).ToList();

            foreach (Contract.TouringPartyItem item in touringParty.Items)
            {
                item.Vendor = GetRVendorByID(item.Vendor.ID);
            }

            return touringParty;
        }

        public void VoidTouringParty(Contract.TouringParty touringParty, string cause)
        {
            cause = cause.Trim();

            DateTime dateTime = DateTime.Now;

            TouringParty dataTouringParty = (from tto in entities.TouringParty
                                             where tto.ID == touringParty.ID
                                             select tto).SingleOrDefault();
            if (dataTouringParty == null)
                throw new BusinessException(BusinessFail.自助团订单不存在);
            if (dataTouringParty.Status.Trim() == "已作废")
                throw new BusinessException(BusinessFail.自助团订单已作废);
            if (dataTouringParty.CustomerStatus.Trim() == "已付款")
                throw new BusinessException(BusinessFail.客户已付款);
            if (dataTouringParty.VendorStatus.Trim() != "未付款")
                throw new BusinessException(BusinessFail.供应商已支付);

            dataTouringParty.VoidCause = cause;
            dataTouringParty.Status = "已作废";
            dataTouringParty.UpdateTime = dateTime;

            entities.SaveChanges();
        }

        public List<Contract.TourItemType> GetTourItemTypeList()
        {
            return (from tit in entities.TourItemType
                    orderby tit.Seq
                    select new Contract.TourItemType()
                    {
                        ID = tit.ID,
                        Name = tit.Name.Trim(),
                        UM = tit.UM.Trim(),
                        Seq = tit.Seq
                    }).ToList();
        }

        public void UpdateTourItemTypeList(List<Contract.TourItemType> list)
        {
            var tempList = from tit in entities.TourItemType
                           select tit;
            foreach (var tit in tempList)
                entities.DeleteObject(tit);

            for (int i = 0; i < list.Count; i++)
            {
                Contract.TourItemType tourItemType = list[i];
                TourItemType dataTourItemType = new TourItemType();
                dataTourItemType.ID = tourItemType.ID;
                dataTourItemType.Name = tourItemType.Name.Trim();
                dataTourItemType.UM = tourItemType.UM.Trim();
                dataTourItemType.Seq = i;

                entities.AddToTourItemType(dataTourItemType);
            }

            entities.SaveChanges();
        }

        #endregion
    }
}
